<template>
  <div class="transform-plan-container">
    <!-- 左侧树形菜单 -->
    <div class="sidebar">
      <Tree
            v-if="treeData.length > 0"
            :tree-data="treeData"
            :default-expand-all="true"
            :show-line="true"
            :field-names="{
              title: 'label',
              key: 'objTypeId',
              children: 'children'
            }"
            :selectable="false"
          >
            <template #title="{ label, total,objTypeId }">
              <span @click="handleTreeClick(objTypeId)">{{ label }} <span v-if="total !== undefined" style="color:#1890ff;">({{ total }})</span></span>
            </template>
          </Tree>
    </div>
    <!-- 右侧表格区域 -->
    <div class="main-table">
      <div class="actions">
        <a-button @click="showObjTypeModal">选择迁移对象类型</a-button>
        <a-button :disabled="selectedRowKeys.length === 0" @click="saveSwitchPlanList('3')">跳过迁移</a-button>
        <a-button :disabled="selectedRowKeys.length === 0" @click="saveSwitchPlanList('2')">撤销跳过</a-button>
       <!-- <a-button :disabled="selectedRowKeys.length === 0" @click="saveSwitchPlanList('2')">导出</a-button> 
        <a-button :disabled="selectedRowKeys.length === 0" @click="saveSwitchPlanList('2')">批量校正</a-button>-->
       
      </div>
      <Table
        :columns="columns"
        :data-source="tableData"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
        :pagination="pagination"
        row-key="id"
        bordered
        style="margin-top: 12px;"
      >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'migStatus'">
          <span v-if="record.migStatus === '0'">迁移成功</span>
          <span v-if="record.migStatus === '1'">迁移失败</span>
          <span v-if="record.migStatus === '2'">待迁移</span>
          <span v-if="record.migStatus === '3'">已跳过</span>
        </template>
        <template v-if="column.dataIndex === 'switchStatus'">
          <span v-if="record.switchStatus === '0'">转换成功</span>
          <span v-if="record.switchStatus === '1'">转换失败</span>
          <span v-if="record.switchStatus === '2'">待转换</span>
          <span v-if="record.switchStatus === '3'">已跳过</span>
          <span v-if="record.switchStatus === '4'">已修改</span>
        </template>
        <template v-if="column.dataIndex === 'action'" >
          <a-button type="primary" @click="handleExport(record)">查看详情</a-button>
        </template>
      </template>
      </Table>

    </div>
  </div>
  <div class="flex justify-center mt-6">
    <a-button type="primary" @click="prev" style="margin-right: 10px;">上一步</a-button>
    <a-button type="primary" @click="next">下一步</a-button>
  </div>
  <Modal
    v-model:visible="objTyoeModal"
    title="选择迁移对象类型"
    @ok="handleOk"
    @cancel="handleCancel"
  >

   <CheckboxGroup
   class="dev-checkbox-group"
          :options="objTypeList"
          v-model:value="objTypeListSelected"

          @change="onCheckedTypesChange"
        >
        <template #label="{ objType ,id}">
          <span >{{ objType }}</span>
        </template>
      </CheckboxGroup>
  </Modal>
  <!-- 详情弹窗 -->
<SQLdetails  ref="SQLdetailsRef" />
</template>

<script setup>
import { ref, reactive, defineEmits,onMounted } from 'vue';
import { Tree ,Table,Modal,Checkbox,CheckboxGroup,message,Drawer} from 'ant-design-vue'
import * as http from '@/api/flow/details';
import SQLdetails from './details.vue'
import store from "@/store";
// 树形菜单数据
const treeData = ref([]);
const objTyoeModal = ref(false);
const SQLdetailsRef = ref(null);
// 表格数据和列
const columns = [
  { title: 'schema', dataIndex: 'schema', key: 'schema' },
  { title: '对象名', dataIndex: 'objName', key: 'objName' },
  { title: '对象类型', dataIndex: 'objType', key: 'objType' },
  { title: '迁移状态', dataIndex: 'migStatus', key: 'migStatus' },
  { title: '转换状态', dataIndex: 'switchStatus', key: 'switchStatus' },
  { title: '更新时间', dataIndex: 'updateTime', key: 'updateTime' },
  { title: '操作', dataIndex: 'action', key: 'action' },
];
const tableData = ref([]);
const selectedRowKeys = ref([]);
const onSelectChange = (selectedKeys) =>   {
  selectedRowKeys.value = selectedKeys;
  console.log(selectedRowKeys.value, "selectedRowKeys");
}
const handleExport = (record) => {
  SQLdetailsRef.value.open(record)
}

// 分页配置
const pagination = reactive({
  pageSize: 10,
  total: 65,
  current: 1,
  showTotal: total => `共 ${total} 条`,
  onChange: (page, pageSize) => {
    pagination.current = page
    pagination.pageSize = pageSize
    planList()
  }
})


const selectedObjTypeId = ref('')
const handleTreeClick = (objTypeId) => {
  selectedObjTypeId.value = objTypeId
  planList()
}
// 对获取计划列表
const planList = async () => {
let params = {
  flowId:1751594386615,
  // flowId: store.state.taskInfo.selectMigrationFlow.flowId,
  dbType:store.state.taskInfo.selectMigrationFlow.dbType,
  limit:pagination.pageSize,
  objTypeId:selectedObjTypeId.value,
  offset:(pagination.current-1)*pagination.pageSize,
}
let res = await http.planList(params)
console.log(res, "res");
try{
  if(res.code === '000000'){   
    tableData.value = res.data.row
    pagination.total = res.data.total
    treeData.value = res.data.tree
  }
}catch(error){
  console.log(error, "error");
}
}
const objTypeList = ref([]);
const objTypeListSelected = ref([]);
const onCheckedTypesChange = (val) => {
  objTypeList.value.forEach(item => {
    if(val.includes(item.id)){
      item.isSwitchSelect = 1
    }else{
      item.isSwitchSelect = 0
    }
  })
}
// 获取计划对象类型
const getObjTypeList = async () => {
  let params = {
    flowId:1751594386615,
    // flowId: store.state.taskInfo.selectMigrationFlow.flowId,
  }
  let res = await http.getObjTypeList(params)
  try{
    if(res.code === '000000'){   
      res.data.forEach(item => {
        item.value = item.id
        !item.isSwitchSelect && (item.isSwitchSelect = 0)
        !item.isSelect && (item.isSelect = 0)
      })
      objTypeList.value = res.data
      objTypeList.value.forEach(item => {
        if(item.isSelect == 1){
          item.disabled = false
        }else{
          item.disabled = true
        }
      })
      objTypeListSelected.value = res.data.filter(item => item.isSwitchSelect == 1).map(item => item.id)

      }
  }catch(error){
      console.log(error, "error");
    }
  }
// 更新迁移对象类型
const saveObjTypeList = async () => {
  let params = {
    flowId:1751594386615,
    // flowId: store.state.taskInfo.selectMigrationFlow.flowId,
    list:JSON.stringify(objTypeList.value)
  }
  let res = await http.saveObjTypeList(params)
  try{
    if(res.code === '000000'){
      planList()
    }
  }catch(error){
    console.log(error, "error");
  }
}
// 跳过/撤销跳过
const saveSwitchPlanList = async (type) => {
  let list = [];
  selectedRowKeys.value.forEach(item => {
    list.push({
      id:item,
      switchStatus:type
    })
  })
  let params = {
    flowId:1751594386615,
    // flowId: store.state.taskInfo.selectMigrationFlow.flowId,
    list:JSON.stringify(list)
  }
  let res = await http.saveSwitchPlanList(params)
  try{
    if(res.code === '000000'){
      message.success(res.msg)
      planList()
    }
  }catch(error){
    console.log(error, "error");
  }
}
const handleOk =async () => {
 await saveObjTypeList()
  objTyoeModal.value = false
}
const handleCancel = () => {
 
  objTyoeModal.value = false
}
const showObjTypeModal = () => {
  getObjTypeList()
  objTyoeModal.value = true
}
const emit = defineEmits(['save','next','prev']);
const next = () => emit('next');
const prev = () => emit('prev');
onMounted(() => {
  planList()
 
})
</script>

<style scoped>
.transform-plan-container {
  display: flex;
  /* border: 2px solid #f00; */
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  min-height: 500px;
}
.sidebar {
  width: 240px;
  margin-right: 24px;
  background: #fafafa;
  border-right: 1px solid #eee;
  padding: 12px 0 12px 12px;
}
.main-table {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.actions {
  margin-bottom: 12px;
  display: flex;
  gap: 12px;
}
.dev-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24px 32px;
  margin-bottom: 8px;
}
</style>